<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户权限管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --success-color: #2ecc71;
            --danger-color: #e74c3c;
            --light-color: #ecf0f1;
            --dark-color: #34495e;
        }
        
        body {
            background-color: rgb(255, 255, 255);
            font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
        }
        
        .container {
            margin-top: 30px;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            padding: 25px;
        }
        
        .page-header {
            color: var(--secondary-color);
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .search-box {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 25px;
        }
        
        .table {
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .table th {
            background-color: rgb(250, 250, 250);
            color: #000000;
            font-weight: 500;
            padding: 12px 15px;
        }
        
        .table td {
            padding: 12px 15px;
            vertical-align: middle;
            border-top: 1px solid #eee;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(52, 152, 219, 0.08);
        }
        
        /* 角色标签样式 */
        .role-tag {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 500;
        }

        .role-dormitory {
            background-color: var(--primary-color);
            color: white;
        }

        .role-student {
            background-color: var(--success-color);
            color: white;
        }

        /* 按钮样式 */
        .btn-action {
            padding: 5px 12px;
            font-size: 13px;
            border-radius: 4px;
            margin-right: 5px;
        }

        /* 分页样式 */
        .pagination-container {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }
        
        .pagination {
            margin-left: 35%;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .page-btn:hover {
            background: #f0f0f0;
            border-color: #ccc;
        }
        
        .page-number {
            padding: 8px 12px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .page-number:hover {
            background: #f0f0f0;
        }
        
        .page-number.active {
            background: var(--primary-color);
            color: white;
        }

        /* 模态框样式 */
        .modal-header {
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
        }

        .btn-prev, .btn-next {
            padding: 6px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
        }
        .btn-prev:hover, .btn-next:hover {
            color: #1890ff;
            border-color: #1890ff;
        }
        .btn-prev:disabled, .btn-next:disabled {
            color: #d9d9d9;
            border-color: #d9d9d9;
            cursor: not-allowed;
        }


        .modal-title {
            color: var(--secondary-color);
            font-weight: 500;
        }
        .modal-backdrop {
            display: none !important;
        }
        .btn-prev{
            padding: 6px 8px;
            background: #edf2f7;
            color: #4a5568;

        }
        .btn-next{
            padding: 6px 8px;
            background: #edf2f7;
            color: #4a5568;

        }
        .pagination{
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="page-header">
        <h2><i class="bi bi-people-fill me-2"></i>用户权限管理</h2>
    </div>
    
    <!-- 搜索表单 -->
    <div class="search-box">
        <form>
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-search"></i></span>
                        <input type="text" class="form-control" placeholder="搜索用户名" name="search" id="search">
                    </div>
                </div>
                <div class="col-md-4">
                    <select class="form-select" id="newRole1">
                        <option value="">所有用户</option>
                        <option value="dormitory">宿管</option>
                        <option value="student">学生</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-primary w-100" onclick="sousuo()" style="background-color: #2d9249">
                        <i class="bi bi-search me-1"></i>搜索
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 用户表格 -->
    <div class="table-responsive">
        <table class="table table-hover" id="t1">
            <thead>
                <tr>
                    <th>用户ID</th>
                    <th>用户名</th>
                    <th>性别</th>
                    <th>电话</th>
                    <th>角色</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb"></tbody>
        </table>
    </div>

    <!-- 在表格下方添加分页控件 -->
    <div class="pagination">
        <button class="btn-prev" onclick="loadPageData(currentPage - 1)">
            <i class="bi bi-chevron-left"></i> 上一页
        </button>

        <span id="pageInfo">第 1 页/共 1 页</span>
        <button class="btn-next" onclick="loadPageData(currentPage + 1)">
            下一页 <i class="bi bi-chevron-right"></i>
        </button>
    </div>
</div>

<!-- 修改角色模态框 -->
<div class="modal fade" id="roleModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改用户角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="roleForm">
                    <input type="hidden" id="userId">
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">当前角色</label>
                        <input type="text" class="form-control" id="currentRole" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">新角色</label>
                        <select class="form-select" id="newRole">

                            <option value="dormitory">宿管</option>
                            <option value="student">学生</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateRole()">确认修改</button>
            </div>
        </div>
    </div>
</div>

</body>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>

        // 在全局变量区域添加
        var currentPage = 1;
        var totalPages = 1;

        // 修改页面加载时的查询函数
        $(document).ready(function() {
            loadPageData(1); // 初始加载第一页
        });

        // 修改渲染用户表格函数，处理两种数据格式
        function renderUserTable(data) {
            try {
                // 处理分页数据格式和非分页数据格式
                let users = data.list ? data.list : (typeof data === 'string' ? JSON.parse(data) : data);
                
                // 移除强制过滤代码，保留原始数据
                let html = "";
                $("#tb").html("");
                $.each(users, function(index, user) {
                    let roleName = '';
                    switch(user.role) {
                        case 'dormitory': roleName = '宿管'; break;
                        case 'student': roleName = '学生'; break;
                        default: roleName = user.role;
                    }
                    
                    html += '<tr>' +
                        '<td>' + user.user_id + '</td>' +
                        '<td>' + user.username + '</td>' +
                        '<td>' + user.sex + '</td>' +
                        '<td>' + user.phone + '</td>' +
                        '<td><span class="role-tag role-' + user.role + '">' + roleName + '</span></td>' +
                        '<td>' +
                        '<button class="btn-primary edit-role-btn" style="background-color: rgb(250, 173, 20); color: white;border: none; border-radius: 5px 5px 5px 5px; width: 50%;height: 60%" ' +
                        'data-userid="' + user.user_id + '" data-username="' + user.username + '" data-role="' + user.role + '">修改角色</button>' +
                        '</td>' +
                        '</tr>';
                });
                
                $("#tb").html(html);
            } catch(e) {
                console.error("渲染表格出错:", e);
            }
        }

        // 修改更新角色后的回调函数
        function updateRole() {
            var userId = document.getElementById('userId').value;
            var newRole = document.getElementById('newRole').value;
            
            $.ajax({
                url: '<%=request.getContextPath()%>/changeController',
                type: 'POST',
                data: {
                    op: 'character',
                    userId: userId,
                    newRole: newRole
                },
                success: function(response) {
                    if(response === '修改成功') {
                        alert('角色更新成功！');
                        var modal = bootstrap.Modal.getInstance(document.getElementById('roleModal'));
                        modal.hide();
                        loadPageData(currentPage); // 重新加载当前页数据
                    } else {
                        alert('角色更新失败：' + response);
                    }
                },
                error: function(xhr, status, error) {
                    alert('请求出错：' + error);
                }
            });
        }

        // 修改loadPageData函数
        function loadPageData(page) {
            currentPage = page;
            $.get('<%=request.getContextPath()%>/changeController',
                { 
                    op: "getAllUsers",
                    page: page,
                    pageSize: 5
                },
                function(data) {
                    try {
                        if(data && data.list) {
                            renderUserTable(data.list);
                            totalPages = data.totalPages;
                            // 更新分页状态
                            $("#pageInfo").text("第 " + currentPage + " 页/共 " + totalPages + " 页");
                            $(".btn-prev").prop("disabled", currentPage <= 1);
                            $(".btn-next").prop("disabled", currentPage >= totalPages);
                        } else {
                            $("#tb").html('<tr><td colspan="6" class="text-center">暂无数据</td></tr>');
                        }
                    } catch(e) {
                        console.error("数据处理错误:", e);
                    }
                }
            ).fail(function() {
                $("#tb").html('<tr><td colspan="6" class="text-center text-danger">数据加载失败</td></tr>');
            });
        }

        // 修改updatePagination函数
        function updatePagination() {
            debugger
        // 更新分页信息显示
        $("#pageInfo").text(`第 ${page==null?1:page} 页/共 ${totalPages==null?1:totalPages} 页`);
        
        // 更新按钮状态
        $(".btn-prev").prop("disabled", currentPage <= 1);
        $(".btn-next").prop("disabled", currentPage >= totalPages);
        
        // 生成页码按钮
        let pageNumbersHtml = '';
        let startPage = Math.max(1, currentPage - 1);
        let endPage = Math.min(totalPages, currentPage + 1);
        
        if (startPage > 1) {
            pageNumbersHtml += `<span class="page-number" onclick="loadPageData(1)">1</span>`;
            if (startPage > 2) {
                pageNumbersHtml += `<span class="page-number disabled">...</span>`;
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            pageNumbersHtml += `<span class="page-number ${i == currentPage ? 'active' : ''}"
                onclick="loadPageData(${i})">${i}</span>`;
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                pageNumbersHtml += `<span class="page-number disabled">...</span>`;
            }
            pageNumbersHtml += `<span class="page-number" onclick="loadPageData(${totalPages})">${totalPages}</span>`;
        }
        
        $("#pageNumbers").html(pageNumbersHtml);
        }

        // 修改搜索函数支持分页
        // 修改搜索函数
        function sousuo() {
            let search = $("#search").val().trim();
            let role = $("#newRole1").val(); // 获取下拉框选中的角色
            
            // 重置到第一页
            currentPage = 1;
            
            $.get('<%=request.getContextPath()%>/changeController',
                { 
                    op: "chaxu",
                    seach: search,
                    newRole1: role,  // 传递选中的角色
                    page: 1,
                    pageSize: 5
                },
                function(data) {
                    if(data && data.list) {
                        // 根据选择的角色进行过滤
                        let filteredList = data.list;
                        if(role) { // 如果选择了特定角色
                            filteredList = data.list.filter(user => user.role === role);
                        }
                        renderUserTable(filteredList);
                        totalPages = data.totalPages;
                        updatePagination();
                    } else {
                        $("#tb").html('<tr><td colspan="6" class="text-center">未找到匹配的用户</td></tr>');
                    }
                }
            ).fail(function() {
                $("#tb").html('<tr><td colspan="6" class="text-center text-danger">搜索失败</td></tr>');
            });
        }

    // 页面加载时查询所有用户
    $(document).ready(function() {
        $.get('<%=request.getContextPath()%>/changeController', 
            { op: "getAllUsers" },
            function(data) {
                try {
                    if(data && data !== "") {
                        renderUserTable(data);
                    } else {
                        console.log("未获取到用户数据");
                    }
                } catch(e) {
                    console.error("数据处理错误:", e);
                }
            }
        ).fail(function(jqXHR, textStatus, errorThrown) {
            console.error("请求失败:", textStatus, errorThrown);
        });
    });

    
    
    // 修改showRoleModal函数：
    // 修改showRoleModal函数
    function showRoleModal(userId, username, role) {
        document.getElementById('userId').value = userId;
        document.getElementById('username').value = username;
        
        // 当前角色转换为中文显示
        let currentRoleName = '';
        switch(role) {
            case 'dormitory': currentRoleName = '宿管'; break;
            case 'student': currentRoleName = '学生'; break;
            default: currentRoleName = role;
        }
        document.getElementById('currentRole').value = currentRoleName;
        
        // 设置新角色下拉框的默认值
        document.getElementById('newRole').value = role;
        
        // 初始化模态框
        var modal = new bootstrap.Modal(document.getElementById('roleModal'));
        modal.show();
    }
    
    // 更新角色
    function updateRole() {
        var userId = document.getElementById('userId').value;
        var newRole = document.getElementById('newRole').value;
        
        $.ajax({
            url: '<%=request.getContextPath()%>/changeController',
            type: 'POST',
            data: {
                op: 'character',
                userId: userId,
                newRole: newRole
            },
            success: function(response) {
                if(response === '修改成功') {
                    alert('角色更新成功！');
                    // 关闭模态框
                    var modal = bootstrap.Modal.getInstance(document.getElementById('roleModal'));
                    modal.hide();
                    
                    // 重新查询用户数据
                    $.get('<%=request.getContextPath()%>/changeController', 
                        { op: "getAllUsers" },
                        function(data) {
                            try {
                                if(data && data !== "") {
                                    renderUserTable(data);
                                } else {
                                    console.log("未获取到用户数据");
                                }
                            } catch(e) {
                                console.error("数据处理错误:", e);
                            }
                        }
                    ).fail(function(jqXHR, textStatus, errorThrown) {
                        console.error("请求失败:", textStatus, errorThrown);
                    });
                    
                } else {
                    alert('角色更新失败：' + response);
                }
            },
            error: function(xhr, status, error) {
                alert('请求出错：' + error);
            }
        });
    }

    // 修改事件委托处理函数
    $(document).on('click', '.edit-role-btn', function() {
        var userId = $(this).data('userid');
        var username = $(this).data('username');
        var role = $(this).data('role');
        showRoleModal(userId, username, role);
    });
</script>

</body>
<!-- 在表格下方添加分页控件 -->
<%--<div class="pagination">--%>
<%--    <button class="btn-prev" onclick="loadPageData(currentPage - 1)">--%>
<%--        <i class="bi bi-chevron-left"></i> 上一页--%>
<%--    </button>--%>
<%--    <div id="pageNumbers"></div>--%>
<%--    <span id="pageInfo">第 1 页/共 1 页</span>--%>
<%--    <button class="btn-next" onclick="loadPageData(currentPage + 1)">--%>
<%--        下一页 <i class="bi bi-chevron-right"></i>--%>
<%--    </button>--%>
<%--</div>--%>
</html>